<?php

class Wechat{

    const _CONST_TB_WEIXIN_ = 'weixin_bind';

	//签名
    private $token = 'm4eeee';

    //消息类型
    private $msgtype;

    //消息内容
    private $msgobj;

    //事件类型
    private $eventtype;

    //事件key值
    private $eventkey;

	#{服务号才可得到
    //AppId
    private $appid = "wxfe88d70ab6684c79";
    //AppSecret
    private $secret = "cf9f3c5443a2e0a89e00c6f6a17a484d";
	#}
	
	private $_isvalid = false;
	
	public function __construct($token,$isvalid = false){
		$this->token = $token;
		$this->_isvalid = $isvalid;
	}
	
	/**
	 *	执行程序入口
	 */
	public function index(){
		if($this->_isvalid){
			$this->valid();
		}
		$this->getMsg();
		$this->responseMsg();
	}

	/**
     *  初次校验
     */
	private function valid(){
        $echoStr = $_GET["echostr"];

        if($this->checkSignature()){
        	echo $echoStr;
        	exit();
        }
    }

    /**
     *  创建自定义菜单
     */
    public function createMenu(){
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->getAccessToken();
        $menujson = '{
            "button":[
                {
                    "name":"我的",
                    "sub_button":[
                        {
                            "type":"click",
                            "name":"我的身份",
                            "key":"V1001_MINE"
                        },

                        {
                            "type":"click",
                            "name":"我的数据",
                            "key":"V1001_DATA"
                        }
                    ]
               },
                {
                    "type":"click",
                    "name":"结算",
                    "key":"V1001_CHECKIN"
                },
                {
                    "type":"view",
                    "name":"帮助",
                    "url":"http://www.zhyxia.com/help"
                }
            ]
        }';

        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$menujson);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

        $info = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Errno'.curl_error($ch);
        }

        curl_close($ch);

        var_dump($info);
    }

    /**
     *  删除自定义菜单
     */
    private function deleteMenu(){
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$this->getAccessToken();

        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

        $info = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Errno'.curl_error($ch);
        }

        curl_close($ch);

        var_dump($info);

    }

    /**
     *  获取消息
     */
    private function getMsg(){
        //验证消息的真实性
        if(!$this->checkSignature()){
            exit();
        }

        //接收消息
        $poststr = $GLOBALS["HTTP_RAW_POST_DATA"];
        //Kohana::$log->add(Log::DEBUG, $poststr);
        if(!empty($poststr)){
            $this->msgobj = simplexml_load_string($poststr,'SimpleXMLElement',LIBXML_NOCDATA);
            $this->msgtype = strtolower($this->msgobj->MsgType);
        }
        else{
            $this->msgobj = null;
        }
    }

    /**
     *  回复消息
     */
    private function responseMsg(){
        switch ($this->msgtype) {
            case 'text':
                $data = $this->getData($this->msgobj->Content);
                if(empty($data) || !is_array($data)){
			if (empty($data))
				$content = "请点击菜单，查看帮助";
			else
			{
				if ($data == '解除绑定')
				{
					$this->unbind_passport($this->msgobj->FromUserName);
					return;
				}
				else if (strpos($data, 'CPA') !== FALSE || strpos($data, 'cpa') !== FALSE)
				{
					$content = WeixinManager::cpa_data(self::currentUser());
				}
                else if (strpos($data, '营业厅') !== FALSE || strpos($data, '直营厅') !== FALSE)
                {
					$content = WeixinManager::bjmobile_list(self::currentUser());
                }
				else
				{
                    			$content = "你好你好";
				}
			}
                	$this->textMsg($content);//查询不到记录返回提示信息
                }
                else{
                	//$this->newsMsg($data);
                	$this->textMsg("测试");//查询不到记录返回提示信息
                }
                break;
            case 'event':
                $this->eventOpt();
                break;
            default:
                # code...
                $this->textMsg("其他测试");//查询不到记录返回提示信息
                break;
        }
    }

    /**
     *  回复文本消息
     */
    private function textMsg($content=''){
        $textxml = "<xml><ToUserName><![CDATA[{$this->msgobj->FromUserName}]]></ToUserName><FromUserName><![CDATA[{$this->msgobj->ToUserName}]]></FromUserName><CreateTime>".time()."</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
        
        //做搜索处理
        if(empty($content)){
            $content = "查询功能正在开发中...";
        }
        $resultstr = sprintf($textxml,$content);
        echo $resultstr;
    }

    /**
     *  回复图文消息
     */
    private function newsMsg($data){
        if(!is_array($data)){
        	exit();
        }
        $newscount = (count($data) > 10)?10:count($data);
        $newsxml = "<xml><ToUserName><![CDATA[{$this->msgobj->FromUserName}]]></ToUserName><FromUserName><![CDATA[{$this->msgobj->ToUserName}]]></FromUserName><CreateTime>".time()."</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>{$newscount}</ArticleCount><Articles>%s</Articles></xml>";
        $itemxml = "";
        foreach ($data as $key => $value) {
        	$itemxml .= "<item>";
        	$itemxml .= "<Title><![CDATA[{$value['title']}]]></Title><Description><![CDATA[{$value['summary']}]]></Description><PicUrl><![CDATA[{$value['picurl']}]]></PicUrl><Url><![CDATA[{$value['url']}]]></Url>";
        	$itemxml .= "</item>";
        }
        $resultstr = sprintf($newsxml,$itemxml);
        echo $resultstr;
    }

    /**
     *  事件处理
     */
    private function eventOpt(){
        $this->eventtype = strtolower($this->msgobj->Event);
        switch ($this->eventtype) {
            case 'subscribe':

                //做用户绑定处理

                $content = "ruiblog";
                $this->textMsg($content);
                break;
            case 'unsubscribe':
                
                //做用户取消绑定的处理

                break;
            case 'click':
                $this->menuClick();
                break;
            default:
                # code...
                break;
        }
    }

    /**
     *  自定义菜单事件处理
     */
    private function menuClick(){
        $this->eventkey = $this->msgobj->EventKey;
        $wid = $this->msgobj->FromUserName;
        switch ($this->eventkey) {
            case 'V1001_MINE':
                $user = self::currentUser();
                if (empty($user))
                    $this->textMsg("<a href=\"http://www.zhyxia.com/weixin/bind?wid=$wid\">请绑定账户</a>");
                else
                    $this->msg_my_info($user);
                break;

            case 'V1001_DATA' :
                $user = self::currentUser();
                if (empty($user))
                    $this->textMsg("<a href=\"http://www.zhyxia.com/weixin/bind?wid=$wid\">请绑定账户</a>");
                else
                    $this->msg_my_data($user);
                break;

            case 'V1001_CHECKIN':
                $user = self::currentUser();
                if (empty($user))
                    $this->textMsg("<a href=\"http://www.zhyxia.com/weixin/bind?wid=$wid\">请绑定账户</a>");
                else
                    $this->msg_my_checkin($user);
                break;
            default:
                # code...
                break;
        }
    }

    /**
	 *	获取本地数据
     */
    private function getData($key='ruiblog'){
		$data = $key;
		//写你自己相关的程序
    	return $data;
    }
	
    /**
     *  校验签名
     */
	private function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
		$token = $this->token;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpStr);

		return TRUE;

		
        return ($tmpStr == $signature)?true:false;
	}

    /**
     *  获取access token
     */
    private function getAccessToken(){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->secret";
        $atjson=file_get_contents($url);
        $result=json_decode($atjson,true);//json解析成数组
        if(!isset($result['access_token'])){
            exit( '获取access_token失败！' );
        }
        return $result["access_token"];
    }

    public static function bind_passport($passport, $password, $weixinid)
    {
        if (passport::login($passport, $password, FALSE, FALSE))
        {
            DB::insert(self::_CONST_TB_WEIXIN_)
                ->columns (array('passport', 'weixinid'))
                ->values  (array($passport, $weixinid))
                ->execute();
        }
        else
        {
            throw new Exception_Warn("账户密码不匹配");
        }
    }

    public function unbind_passport($weixinid)
    {
        $rows = DB::delete(self::_CONST_TB_WEIXIN_)
		->where('weixinid', '=', $weixinid)
                ->execute();

	if ($rows > 0)
		$this->textMsg('已解除绑定方寸掌悦账户');
	else
		$this->textMsg('你没有绑定方寸掌悦账户');
	
    }



    private function currentUser()
    {
        $userId = $this->msgobj->FromUserName;
        $query  = DB::select('passport')
                ->from(self::_CONST_TB_WEIXIN_)
                ->where('weixinid', '=', $userId)
                ->execute();

        if ($query->count() > 0)
        {
            $info = $query->current();
            $passport = $info['passport'];
            $user = user::factory($passport);

            return $user;
        }
        else
        {
            return NULL;
        }
    }

    private function msg_my_info($user)
    {
        $uid  = $user->get_user_id();
        $info = $user->get_user_info();
	if ($info['utype'] == 'manager')
		$cmt = WeixinManager::info($user);
	else 
        	$cmt  = Arr::get($info, 'comments', '暂无身份信息');

        if (empty($cmt))
            $cmt = '暂无身份信息';
        $this->textMsg("我的身份:\n----------\n$cmt"); 
    }

    private function msg_my_data($user)
    {
        $uid = $user->get_user_id();
	$info= $user->get_user_info();
        $strs  = "装机数据（手机数量）:\n----------\n";
	if ($info['utype'] == 'manager')
	{
		$strs .= WeixinManager::data($user);
	}
	else
	{
        	$stats = Data::stats($uid, 3);
        	foreach ($stats as $day => $rs)
        	{
            		$strs .= "$day : ". $rs['mobiles'] . "台\n";
        	}
	}
        
        $this->textMsg($strs); 
    }

    private function msg_my_checkin($user)
    {
        $this->textMsg('用户你好，数据结算微信功能正在开发中'); 
    }
}


?>
